package com.linhngua.code.gwt.spring;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePropertySource;

@Configuration
public class ApplicationInitialiser implements
		ApplicationContextInitializer<ConfigurableApplicationContext> {
	
	private static final Logger LOG=LoggerFactory.getLogger(ApplicationInitialiser.class);
	
	public void initialize(ConfigurableApplicationContext applicationContext) {

		ConfigurableEnvironment env = applicationContext.getEnvironment();
		
		MutablePropertySources propSources = ((ConfigurableEnvironment) env)
				.getPropertySources();
		
		try {
			String path = "/config/application.properties";
			Resource resource = new ClassPathResource(path);
			ResourcePropertySource propSource = new ResourcePropertySource(
					resource);
			propSources.addFirst(propSource);
			LOG.info("Common configuration of application:\n"+propSource);
			String profileName = System.getProperty("spring.profiles.active");
			LOG.info("Active profile is "+profileName);
					env.setActiveProfiles(profileName);
			LOG.info(profileName.toUpperCase()+" configuration of  application:\n"+propSource);
			
		}
		catch (IOException e) {
			throw new RuntimeException("cannot load environment", e);
		}
	}
}
